package com.itcpeng.controller;

import com.aliyuncs.exceptions.ClientException;
import com.itcpeng.constant.MessageConstant;
import com.itcpeng.constant.RedisMessageConstant;
import com.itcpeng.entity.Result;
import com.itcpeng.util.SMSUtils;
import com.itcpeng.util.ValidateCodeUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

@RestController
@RequestMapping(value = "/validateCode")
public class ValidateCodeController {

    @Autowired
    private JedisPool jedisPool;

    //预约验证短信
    @PostMapping(value = "/send4Order")
    public Result send4Order(String telephone) {
        try {
            //获取jedis操作对象  用完就关闭
            Jedis jedis = jedisPool.getResource();
            String key = "Order_" + RedisMessageConstant.SENDTYPE_ORDER + "_" + telephone;
            //判断是否发生过了  key值是否存在
            if (jedis.get(key) != null) {
                //redis有值,已经发生过了
                return new Result(true, MessageConstant.SENT_VALIDATECODE);
            }
            //生成验证码
            Integer code = ValidateCodeUtils.generateValidateCode(6);
            //发送验证码
            System.out.println(code);
//            SMSUtils.sendShortMessage(SMSUtils.VALIDATE_CODE, telephone, code + "");
            //存入jedis
            jedis.setex(key, 5 * 60, code + "");
            return new Result(true, MessageConstant.SEND_VALIDATECODE_SUCCESS);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new Result(false, MessageConstant.SEND_VALIDATECODE_FAIL);
    }


    //快速登录验证
    @PostMapping(value = "/send4Login")
    public Result send4Login(String telephone) {
        try {
            //获取jedis操作对象  用完就关闭
            Jedis jedis = jedisPool.getResource();
            String key = "login_" + RedisMessageConstant.SENDTYPE_LOGIN + "_" + telephone;
            //判断是否发生过了  key值是否存在
            if (jedis.get(key) != null) {
                //redis有值,已经发生过了
                return new Result(true, MessageConstant.SENT_VALIDATECODE);
            }
            //生成验证码
            Integer code = ValidateCodeUtils.generateValidateCode(6);
            //发送验证码
            System.out.println(code);
            //存入jedis
            jedis.setex(key, 4 * 60, code + "");
            return new Result(true, MessageConstant.SEND_VALIDATECODE_SUCCESS);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new Result(false, MessageConstant.SEND_VALIDATECODE_FAIL);
    }


}
